import React from 'react'
import { ROOTURL } from './AppConfig'
import { getTimeDistance } from './util'
import { Redirect } from 'react-router-dom'
//公告板
export default class BillboardHistory extends React.Component {

  constructor(props){
    super(props)
    this.redirect = this.redirect.bind(this)
    this.state = {
      postItems: [],
      redirectToCreateNew: false
    }
    fetch(ROOTURL + 'billboardlist.php').then(
        response => response.json()
    ).then(json => {
        this.setState({
            postItems: json.result
        })
    }).catch(
        error => {alert('网络错误无法加载公告: '+ error.toString())}
    )
  }
    redirect(){
        this.setState({redirectToCreateNew : true})
    }
    render() {
        if(this.state.redirectToCreateNew){
            return <Redirect to="/billboardCreate" />
        }
        const postItemList = this.state.postItems.map((item) => {
            let timeDistance = getTimeDistance(item.createdate)
            return (
                <div key={item.id} className="billBoardItem">
                    <div> {item.title} </div>
                    <div> {timeDistance} </div>
                    <div> {item.text} </div>
                </div>
             )
            })
        return (
            <div>              
              <div className='billBoardIndex'>
                    公告
              </div>
                <div className="billBoardList">{postItemList}</div>
                <div className="bottomButtonWrapper">
                    <button className="btn btn-primary" onClick={this.redirect}>新建公告</button>
                </div>
            </div>
        )
  }
}

